import './index_PC.scss';
import React, { useEffect, useState, useRef } from "react";
import { get_token_list, get_balance_of, transfer_gas_fee, user_submit_order } from '@/utils/mixin.ts'
import { Button, Form, Input, Select, message, Spin} from 'antd';
import { Popup, Space } from 'antd-mobile'
import { ArrowLeftOutlined, CopyOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import ic from '@/assets/photos/ic.png';

const Transfer = () => {
    const { Option } = Select;
    const [walletList, setWalletList] = useState([]);
    const [toValue, setToValue] = useState('');
    const [gasFee, setGasFee] = useState(null);
    const [visible, setVisible] = useState(false);
    const [tokenAddress, setTokenAddress] = useState(JSON.parse(localStorage.getItem('detail')).address);
    const [balance, setBalance] = useState('');
    const [address, setAddress] = useState('')
    const [token, setToken] = useState(null)
    const [Amont, setAmont] = useState(null)
    const inputRef = useRef(null);
    const [spinning, setSpinning] = React.useState(false);

    useEffect(() => {
        get_token_list({
            network: JSON.parse(localStorage.getItem('detail')).keyNode,
            email: localStorage.getItem('email'),
            wallet_id: JSON.parse(localStorage.getItem('detail')).wallet_id,

        }).then(res => {
            if (res) {
                setWalletList(res.data);
                setToken(()=> {
                    const data = res.data.length ? res.data[0].address : null
                    return data
                })
            } else {
            }
        });
    }, []);  // 空数组表示只在组件挂载时执行

    // toInput失焦获取
    const toInputBlur = async () => {
        setSpinning(true);
        await get_balance_of({
            network: JSON.parse(localStorage.getItem('detail')).keyNode,
            token: token,
            address: tokenAddress,

        }).then(res => {
            if (res) {
                setBalance(res.data.balance);
            } else {
            }
        });
        await transfer_gas_fee({
            network: JSON.parse(localStorage.getItem('detail')).keyNode,
            email: localStorage.getItem('email'),
            wallet_id: localStorage.getItem('wallet_id'),
            token: token,
            from: tokenAddress  ,
            to: toValue

        }).then(res => {
            setSpinning(false);
            if (res) {
                setGasFee(res.data.gas_fee);
            } else {
            }
        });
    }

    useEffect(() => {
        if(!toValue) return
        // 定义一个定时器，延迟调用接口
        const timer = setTimeout(() => {
            toInputBlur();
        }, 500); // 设置延迟时间，可以根据实际情况调整

        // 在下一次 useEffect 调用前清除定时器，确保只有最后一次输入结束后才调用接口
        return () => clearTimeout(timer);
    }, [toValue]); // 监听 token_address 的变化

    // 复制
    const copyToClipboard = (text) => {
        const tempInput = document.createElement('input');
        tempInput.value = text;
        document.body.appendChild(tempInput);
        tempInput.select();
        tempInput.setSelectionRange(0, 99999);
        document.execCommand('copy');
        document.body.removeChild(tempInput);
        message.success('复制成功');
      };
    const onGenderChange = async (e) => {
        console.log(e)
        await setToken(e)
    }

    const txtDis = (str) => {
        if(!str) return
        const firstFour = str.slice(0, 4);
        const lastFour = str.slice(-4);
        const maskedString = `${firstFour}****${lastFour}`;
        return maskedString;
      };
      
    const submit = () => {
        const data = JSON.parse(localStorage.getItem('detail'))
        let query = null
        setVisible(false)
        if(token == '0x0000000000000000000000000000000000000000') {
            query = {
                network: data.keyNode,
                email: localStorage.getItem('email'),
                wallet_id: data.wallet_id,
                type:'transfer_eth',
                token_amount: Amont*1,
                to: toValue
              }
        } else {
            query = {
                network: data.keyNode,
                email: localStorage.getItem('email'),
                wallet_id: data.wallet_id,
                type:'transfer_erc20',
                token_amount: Amont*1,
                to: toValue,
                token_name: data.symbol,
                token_address: token
              }
        }
        setSpinning(true);
        user_submit_order(query).then(res => {
            setSpinning(false);
            if(res.code == 0) {
                message.success('操作成功')
                window.history.go(-1)
            } else if (res.msg == 'insufficient_tokens'){
                message.error('余额不足')
            } else {
                message.error(res.msg)
            }
           
          })
    }

    useEffect(() => {
        if(!toValue) return
        toInputBlur()
    }, [token]);
    return (
        <div className="transfer">
            <Spin spinning={spinning} fullscreen />
            <div className="header">
                <Button type="text" className="goBackBtn" onClick={() => window.history.go(-1)} icon={<ArrowLeftOutlined />}></Button>
                <p className="title">Transfer</p>
            </div>
            <div className="content">
                <Form
                    name="basic"
                    labelCol={{
                        span: 8,
                    }}
                    wrapperCol={{
                        span: 16,
                    }}
                    style={{
                        maxWidth: 400,
                    }}
                >
                    <Form.Item
                        label="Token"
                    >
                        <Select
                            key={token && token}
                            defaultValue={token && token}
                            onChange={onGenderChange}
                            allowClear
                        >
                            {
                                walletList.map(item => {
                                    return <Option key={item.name} value={item.address}>{item.name}</Option>
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="To"
                    >
                        <Input placeholder='To' ref={inputRef} value={toValue} onChange={(e) => { setToValue(e.target.value) }} />
                    </Form.Item>

                    <Form.Item
                    className='label-avai'
                        label={
                            <p className='Available'>
                                <span>Amont</span>
                                <span>Available: {balance} {JSON.parse(localStorage.getItem('detail')).symbol}</span>
                            </p>
                        }
                    >
                        <Input placeholder='Amont' value={Amont} onChange={(e)=> setAmont(e.target.value)}  suffix={
                            <span onClick={() => {setAmont(balance)}}>All</span>
                        } />
                    </Form.Item>
                    <Form.Item
                        label="Gas Fees"
                    >
                        <Input className='gasFeeInput'></Input>
                        <div className='gasFeeText'>
                            <span>{gasFee ? gasFee.eth_amount : ''}</span>
                            <span>{gasFee ? gasFee.usd_amount : ''}</span>
                        </div>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" onClick={() => setVisible(true)}>
                            Next
                        </Button>
                    </Form.Item>
                </Form>
            </div>
            <div className='showDialog'>
                <Popup
                    visible={visible}
                    // showCloseButton
                    onMaskClick={() => {
                        setVisible(false)
                    }}
                    onClose={() => {
                        setVisible(false)
                    }}
                    position='top'
                    bodyStyle={{ height: '40vh' }}
                >
                    <div className='transfer_dialogContent'>
                        <div className='header_dialog'>
                            <span className='title'>Transfer Confirmation</span>
                            <div>
                                <img src={ic}/>
                                <span>{Amont} {JSON.parse(localStorage.getItem('detail')).symbol}</span>
                            </div>
                        </div>
                        <div className='content_dialog'>
                            <p>
                                <span>Transfer to address</span>
                                <span>{txtDis(toValue)}</span>
                                <Button type="text" className="copyBtn" onClick={() => copyToClipboard(toValue)} icon={<CopyOutlined />}></Button>
                            </p>
                            <p>
                                <span>Transfer out address</span>
                                <span>{txtDis(tokenAddress)}</span>
                                <Button type="text" className="copyBtn" onClick={() => copyToClipboard(tokenAddress)} icon={<CopyOutlined />}></Button>
                            </p>
                            <p>
                                <span>Gas Fees</span>
                                <span> - {gasFee ? gasFee.eth_amount : ''} BNB</span>
                            </p>
                            <div className='optionButton'>
                                <Button onClick={() => setVisible(false)}>取消</Button>
                                <Button type="primary" onClick={(() => submit())}>确定</Button>
                            </div>
                        </div>
                    </div>
                </Popup>
            </div>
        </div>
    )

}

export default Transfer;